package com.pn.warehouse.controller;

import com.pn.warehouse.entity.InStore;
import com.pn.warehouse.entity.Purchase;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.entity.Store;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.PurchaseService;
import com.pn.warehouse.service.StoreService;
import com.pn.warehouse.utils.TokenUtils;
import com.pn.warehouse.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/purchase")
@RestController
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 添加采购单
     */
    @RequestMapping("/purchase-add")
    public Result addPurchase(@RequestBody Purchase purchase){
        //1、执行业务并返回
        Result result = purchaseService.insertPurchase(purchase);
        return result;
    }

    /**
     * 查询所有的仓库
     */
    @RequestMapping("/store-list")
    public Result storeList(){
        //1、执行业务并返回
        List<Store> allStore = storeService.findAllStore();
        return Result.ok(allStore);
    }

    /**
     * 分页查询采购单信息
     */
    @RequestMapping("/purchase-page-list")
    public Result purchasePageList(Page page, Purchase purchase){
        //1、执行业务并返回
        page = purchaseService.queryPurchasePage(page, purchase);
        return Result.ok(page);
    }

    /**
     * 删除采购单
     */
    @RequestMapping("/purchase-delete/{purchaseId}")
    public Result deletePurchase(@PathVariable Integer purchaseId){
        //1、执行业务并返回
        Result result = purchaseService.removePurchaseById(purchaseId);
        return result;
    }

    /**
     * 修改采购单
     */
    @RequestMapping("/purchase-update")
    public Result updatePurchase(@RequestBody Purchase purchase){
        //1、执行业务并返回
        Result result = purchaseService.setNumById(purchase);
        return result;
    }

    /**
     * 生成入库单
     */
    @RequestMapping("/in-warehouse-record-add")
    public Result addInStore(@RequestBody Purchase purchase, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //1、拿到当前用户的id
        int userId = tokenUtils.getCurrentUser(token).getUserId();

        //2、创建inStore对象并封装其信息
        InStore inStore = new InStore();
        inStore.setStoreId(purchase.getStoreId());
        inStore.setProductId(purchase.getProductId());
        inStore.setInNum(purchase.getFactBuyNum());
        inStore.setCreateBy(userId);

        //3、执行业务并返回
        Result result = purchaseService.insertInStore(inStore, purchase.getBuyId());
        return result;
    }

}
